﻿using System;
using ATM.Terminal.Rendering;
using ATM.Terminal.Rendering.Base;
using ATM.Terminal.Screens;
using ATM.Terminal.Screens.Base;

namespace ATM.Terminal
{
    class Program
    {
        private static ScreenBase _currentScreen;
        private static RenderTargetBase _currentRenderTarget;
        private static bool _terminalClosing;

        static void Main()
        {
            //Initialize a render target, Console in this case.
            _currentRenderTarget = new ConsoleRenderTarget();

            //Initialize with the WelcomeScreen as default.
            _currentScreen = new WelcomeScreen();
            _currentScreen.OnScreenChange += OnScreenChange;

            //Run the ATM application.
            Run();
        }

        private static void Run()
        {
            //Run untill the user stops the application with Escape.
            while (!_terminalClosing)
            {
                //Render screen.
                _currentScreen.Render(_currentRenderTarget);

                //Read input from the user.
                var userInput = Console.ReadKey();

                switch (userInput.Key)
                {
                    case ConsoleKey.Escape:
                        _terminalClosing = true;
                        break;
                    default:
                        _currentScreen.ProcessInput(userInput);
                        break;
                }
            }
        }

        private static void OnScreenChange(ScreenBase screen)
        {
            //Detach the old event.
            _currentScreen.OnScreenChange -= OnScreenChange;

            //Set the new screen as current.
            _currentScreen = screen;

            //Attach the new event.
            _currentScreen.OnScreenChange += OnScreenChange;
        }
    }
}
